package com.aisi.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.aisi.commonService.exception.AiSiException;
import com.aisi.manager.mapper.SysRoleUserMapper;
import com.aisi.manager.mapper.SysUserMapper;
import com.aisi.manager.service.SysUserService;
import com.aisi.model.dto.system.AssginRoleDto;
import com.aisi.model.dto.system.LoginDto;
import com.aisi.model.dto.system.SysUserDto;
import com.aisi.model.entity.system.SysRole;
import com.aisi.model.entity.system.SysRoleUser;
import com.aisi.model.entity.system.SysUser;
import com.aisi.model.vo.common.ResultCodeEnum;
import com.aisi.model.vo.system.LoginVo;
import com.aisi.model.vo.system.ValidateCodeVo;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: shenjianZ
 * @Date: 2024/2/16 19:37
 * @Description:
 */

@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;
    ;

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private SysRoleUserMapper sysRoleUserMapper;

    /**
     * 根据用户名查询用户数据
     *
     * @param loginDto LoginDto
     * @return LoginVo
     */
    @Override
    public LoginVo login(LoginDto loginDto) {
        String loginDtoCaptcha = loginDto.getCaptcha();
        String validateCodeKey = loginDto.getCodeKey();
        String redisCaptcha = redisTemplate.opsForValue().get("user:validate" + validateCodeKey);
        if (StrUtil.isEmpty(redisCaptcha) || !StrUtil.equalsIgnoreCase(redisCaptcha, loginDtoCaptcha))
            throw new AiSiException(ResultCodeEnum.VALIDATECODE_ERROR);
        this.deleteValidateCode(validateCodeKey);
        String userName = loginDto.getUserName();
        SysUser sysUser = sysUserMapper.getUserInfoByUsername(userName);
        if (sysUser == null)
            throw new AiSiException(ResultCodeEnum.LOGIN_ERROR);
        String database_password = sysUser.getPassword();
        String loginDtoPassword = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        if (!database_password.equals(loginDtoPassword))
            throw new AiSiException(ResultCodeEnum.LOGIN_ERROR);
        LoginVo loginVo = new LoginVo();
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set("user:login" + token, JSON.toJSONString(sysUser), 7, TimeUnit.DAYS);
        loginVo.setToken(token);
        return loginVo;
    }

    /**
     * 获取登录用户信息
     *
     * @param token
     * @return
     */
    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login" + token);
        return JSON.parseObject(userJson, SysUser.class);
    }

    /**
     * 用户退出登录，删除在redis中的用户信息
     *
     * @param token
     * @return
     */
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login" + token);
    }

    @Override
    public PageInfo<SysUser> findSysUserByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(sysUserMapper.findSysUserByPage(sysUserDto));
    }

    @Override
    public void saveSysUser(SysUser sysUser) {
        SysUser dbSysUser = getUserInfo(sysUser.getUserName());
        if (dbSysUser != null) {
            throw new AiSiException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        // 密码加密
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()));
        sysUser.setStatus(1); // 表示正常状态
        sysUserMapper.saveSysUser(sysUser);
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser);
    }

    @Override
    public void deleteSysUserById(Long id) {
        sysUserMapper.deleteSysUserById(id);
    }

    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        sysRoleUserMapper.deleteSysUserByUserId(assginRoleDto.getUserId());

        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        roleIdList.forEach(roleId -> {
                    SysRoleUser sysRoleUser = new SysRoleUser();
                    sysRoleUser.setUserId(assginRoleDto.getUserId());
                    sysRoleUser.setRoleId(roleId);
                    sysRoleUserMapper.saveSysRoleUser(sysRoleUser);
                }
        );
    }


    /**
     * 从Redis中删除指定键对应的值
     *
     * @param validateCodeKey 待删除的键
     */
    private void deleteValidateCode(String validateCodeKey) {
        redisTemplate.delete("user:validate" + validateCodeKey);
    }


}
